# -*- coding: utf-8 -*-
#
# Copyright (C) 2011  Benjamin Heil
#
# This file is part of Feedmail.
#
# Feedmail is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import random
import datetime

from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.template import Context, loader

class AccountProfile(models.Model):
    """
    Extented user profile.
    http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/
    """
    # To add a new field in UserProfile you must also include this field
    # in all forms in account.forms
    user = models.ForeignKey(User, unique=True)
    mail_validated = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        super(AccountProfile, self).save(*args, **kwargs)

    def __unicode__(self):
        return "Profil %s" % (self.user.username)

    class Meta:
        verbose_name = 'Benutzerprofil'
        verbose_name_plural = 'Benutzerprofile'

class AccountActivation(models.Model):
    """
    Model to save an activation_id for every new registration.
    """
    user = models.ForeignKey(User)
    activation_id = models.CharField(max_length=20, unique=True)
    registered = models.DateTimeField()
    only_mail_change = models.BooleanField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.activation_id = self._get_activation_id()
            self.registered = datetime.datetime.now()
        super(AccountActivation, self).save(*args, **kwargs)

    def _get_activation_id(self):
        random.seed()
        while True:
            id = ''
            while len(id) < 20:
                id += chr(random.randint(97, 122))
            try:
                AccountActivation.objects.get(activation_id=id)
            except AccountActivation.DoesNotExist:
                return id


    def is_activation_in_time(self):
        return (datetime.datetime.now() - self.registered < \
                datetime.timedelta(hours=settings.ACCOUNT_HOURS_TO_ACTIVATE))

    def send_activation_mail(self):
        if self.only_mail_change:
            t = loader.get_template('account/mail_confirmation_email.html')
        else:
            t = loader.get_template('account/activation_email.html')
        c = {
            'site_name': settings.SITE_TITLE,
            'root_url_2': settings.ROOT_URL[0:len(settings.ROOT_URL) - 1],
            'sublink': reverse('account_activate', args=[self.activation_id]),
            'hours_to_activate': settings.ACCOUNT_HOURS_TO_ACTIVATE,
            'root_url': settings.ROOT_URL,
        }
        if self.only_mail_change:
            c['sublink'] = reverse('account_mail_confirmation', args=[self.activation_id])
            # When changing mail only set account active again, but disabled mail_validated state
            # So the user can login, but will get a hint to validate the mail
            self.user.is_active = True
            self.user.save()
            profile = AccountProfile.objects.get(user=self.user)
            profile.mail_validated = False
            profile.save()
        self.user.email_user(u'Aktivierungsmail von %s' % (settings.SITE_TITLE),
                             t.render(Context(c)))

    def __unicode__(self):
        return "%s | %s | %s" % (self.registered.strftime(settings.DATETIME_FORMAT),
                                 self.user.username, self.activation_id)

    class Meta:
        verbose_name = 'Benutzeraktivierung'
        verbose_name_plural = 'Benutzeraktivierungen'
